<?php
// 定义一个类
    class Db{
        private $host;
        private $root;
        private $pwd;
        private $database;
        private $port;
        private $charset;
        public $link;
        public function __construct($params)
        {
            // 初始化属性
            $this->init($params);
            $this->connect();
            // 创建数据库对象
        }
        private function init($parmas=array()){
            $this->host=$parmas['host']??'localhost';//isset($parmas['host'])?$parmas['host']:'localhost'
            $this->root=$parmas['root']??'root';
            $this->pwd=$parmas['pwd']??'123';
            $this->database=$parmas['database'];
            $this->port=$parmas['port']??'3306';
            $this->charset=$parmas['charset']??'ust8';
        }
        private function connect(){
            $this->link=@mysqli_connect($this->host,$this->root,$this->pwd,$this->database);
            if(!$this->link){
                echo "数据库连接失败".mysqli_error($this->link);
            }
            mysqli_set_charset($this->link,$this->charset);
        }
        //执行增删改查
        public function execute($sql){
            if(!$result=mysqli_query($this->link,$sql)){
                echo "sql语句执行错误".mysqli_error($this->link);
                echo "<br>错误的是sql语句是".$sql;
                exit;
            }
            return $result;
        }
        // 查询
        public function select($sql,$type="num"){
            $result=$this->execute($sql);
            $type=$this->gettype($type);
            if((mysqli_num_rows($result))>0){
                return mysqli_fetch_all($result,$type);
                // foreach 
            }
        }
        //查询返回数组类型
        private function gettype($type="MYSQLI_ASSOC"){
            if($type=='assoc'){
                $type=MYSQLI_ASSOC;
            }else if($type=='num'){
                $type=MYSQLI_NUM;
            }else{
                $type=MYSQLI_BOTH;
            }
            return $type;
        }
    }

?>